part of YOSS;

class _YOSSCore {
  _YOSSCore._internal();

  static final _ = _YOSSCore._internal();

  factory _YOSSCore() => _;

  _YOSSOption? _options;

  void init(YOSSOption options) {
    _options = options;
    Client.init(
      ossEndpoint: options.ossEndpoint,
      bucketName: options.bucketName,
      authGetter: () {
        return Auth(
          accessKey: options.accessKey,
          accessSecret: options.accessSecret,
          secureToken: options.secureToken ?? "",
          expire: options.expire ?? "",
        );
      },
    );
  }

  void upload({
    required List<String> filepaths,
    String? dir,
    Function(int fileIndex, int count, int total)? onProgress,
    Function(bool isSuccess, List<String>? urls, String? error)? onFinish,
  }) async {
    try {
      if (filepaths.isEmpty) {
        onFinish?.call(false, null, "上传文件不能为空");
        return;
      }
      if (_options == null) {
        onFinish?.call(false, null, "未初始化SDK");
        return;
      }
      List<String> results = [];
      final userModel = (await AppUtils.readUserModel())!;
      for (var i = 0; i < filepaths.length; i++) {
        final response = await Client().putObjectFile(
          filepaths[i],
          fileKey: "service/yim_${userModel.yim_user}/${dir ?? "default"}/${DateTime.now().microsecondsSinceEpoch}_${Random().nextInt(9999999)}_${filepaths[i].split("/").last}",
          option: PutRequestOption(
            override: false,
            aclModel: AclMode.publicRead,
            storageType: StorageType.standard,
            onSendProgress: (count, total) {
              onProgress?.call(i, count, total);
            },
          ),
        );
        if (response.statusCode != HttpStatus.ok) {
          onFinish?.call(false, null, response.statusMessage ?? "HTTP ${response.statusCode ?? "Unknown"}");
          return;
        }
        results.add(response.requestOptions.path);
        if (results.length >= filepaths.length) onFinish?.call(true, results, null);
      }
    } catch (e) {
      onFinish?.call(false, null, e.toString());
    }
  }

  String ossVideo2Image(String videoOssUrl) {
    return "$videoOssUrl?x-oss-process=video/snapshot,t_1000,m_fast";
  }
}
